package stackandqueue.stack.sequentialdoublestack;

public class SqDoubleStack {
    private int top1;
    private int top2;
    private int maxSize = 512;
    private char[] arr;

    public SqDoubleStack() {
        top1 = -1;
        top2 = maxSize;
        arr = new char[maxSize];
    }

    /**
     * 入栈
     *
     * @param e           入栈元素
     * @param stackNumber 栈号参数，1表示栈1，2表示2
     */
    public void push(char e, int stackNumber) {
        if (top1 + 1 == top2) {
            return;
        }
        if (stackNumber == 1) {
            arr[++top1] = e;
        } else if (stackNumber == 2) {
            arr[--top2] = e;
        }
    }

    /**
     * 出栈
     *
     * @param stackNumber 栈号参数，1表示栈1，2表示栈2
     * @return
     */
    public char pop(int stackNumber) {
        if (top1 + 1 == top2) {
            return '\0';
        }
        if (stackNumber == 1) {
            return arr[top1--];
        } else if (stackNumber == 2) {
            return arr[top2++];
        }
        return '\0';
    }

    /**
     * 栈是否为空，为空返回true，不为空返回false
     *
     * @param stackNumber 栈号参数，1表示栈1，2表示栈2
     * @return
     */
    public boolean stackEmpty(int stackNumber) {
        if (stackNumber == 1) {
            return top1 == -1;
        } else if (stackNumber == 2) {
            return top2 == maxSize;
        } else {
            return true;
        }
    }

    /**
     * 清空栈
     *
     * @param stackNumber 栈号参数，1表示栈1，2表示栈2
     */
    public void clearStack(int stackNumber) {
        if (stackNumber == 1) {
            top1 = -1;
        } else if (stackNumber == 2) {
            top2 = maxSize;
        }
    }

    /**
     * 返回栈顶元素
     *
     * @param stackNumber 栈号参数，1表示栈1，2表示栈2
     * @return
     */
    public char getTop(int stackNumber) {
        if (stackNumber == 1 && top1 != -1) {
            return arr[top1];
        } else if (stackNumber == 2 && top2 != maxSize) {
            return arr[top2];
        }
        return '\0';
    }

    /**
     * 返回栈中元素个数
     *
     * @param stackNumber 栈号参数，1表示栈1，2表示栈2
     * @return
     */
    public int stackLength(int stackNumber) {
        if (stackNumber == 1) {
            return top1 + 1;
        } else if (stackNumber == 2) {
            return maxSize - top2;
        }
        return 0;
    }
}
